// ==UserScript==
// @name         Hu60 Plugins
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You
// @match        https://hu60.cn/q.php/**
// @grant        none
// ==/UserScript==

(function() {
    window.FUN_UTIL = function() {
        if('hu60.cn' !== window.location.host){
            return
        }
        //重复请求统计
        let reloadRequestCount = 0;
        return {
            uploadFile: (file) => {
                /*
                if(file.size && file.size / 1024 > 2048){
                    FUN_UTIL.showToast('文件太大了，老虎要生气了');
                    return;
                }
                */
                FUN_UTIL.loading();
                FUN_UTIL.getToken({
                    succ: (upToken) => {
                        FUN_UTIL.getUpUrl({
                            succ: (upUrl) => {
                                let formData = new FormData();
                                let suffix = FUN_UTIL.getFileSuffix(file.name);
                                let randomStr = Math.random().toString(10).slice(2,6);
                                let upKey = 'file-' + 'time-' + suffix + '-' + new Date().getTime() + randomStr + '.' + suffix;
                                formData.append("name", file.name);
                                formData.append("chunk", 0);
                                formData.append("chunks", 1);
                                formData.append("key", upKey);
                                formData.append("token", FUN_UTIL.getCache('upToken'));
                                formData.append("file", file);
                                $.ajax({
                                    url: FUN_UTIL.getCache('upUrl'),
                                    type: 'POST',
                                    // 告诉jQuery不要去设置Content-Type请求头
                                    contentType: false,
                                    // 告诉jQuery不要去处理发送的数据
                                    processData: false,
                                    data: formData,
                                    success: (res) => {
                                        FUN_UTIL.showToast('上传成功', 1000);
                                        let fileUBBStr = '《图片：' + 'https://' + FUN_UTIL.getCache('upHost') + '/' + res.key + '，' + file.name + '》';
                                        $('#content').val($('#content').val() + fileUBBStr);
                                    },
                                    error: (e) => {
                                        if(e.status === 401 || (e.responseJSON && e.responseJSON.error === 'expired token')){
                                            if(reloadRequestCount === 5){
                                                alert('错误');
                                                return;
                                            }
                                            FUN_UTIL.setCache('upToken', '');
                                            FUN_UTIL.inputDomChange($('#my_hide_file')[0]);
                                            reloadRequestCount++;
                                        }else{
                                            alert('错误');
                                        }
                                    }
                                })
                            }
                        })
                    }
                })
            },
            //初始化
            init: () => {
                let faceList = [{"value":"e4b88de9ab98e585b4.gif","name":"不高兴"},{"value":"e5a4aae5bc80e5bf83.gif","name":"太开心"},{"value":"e58b89e5bcba.gif","name":"勉强"},{"value":"e58d87e8b5b7.gif","name":"升起"},
                                {"value":"e59090e8888c.gif","name":"吐舌"},{"value":"e591b5e591b5.gif","name":"呵呵"},{"value":"e79da1e8a789.gif","name":"睡觉"},{"value":"e998b4e999a9.gif","name":"阴险"},{"value":"e59388e59388.gif","name":"哈哈"},
                                {"value":"e9bb91e7babf.gif","name":"黑线"},{"value":"e5a794e5b188.gif","name":"委屈"},{"value":"e6838ae593ad.gif","name":"惊哭"},{"value":"e6838ae8aeb6.gif","name":"惊讶"},
                                {"value":"e6bb91e7a8bd.gif","name":"滑稽"},{"value":"e5bc80e5bf83.gif","name":"开心"},{"value":"e78b82e6b197.gif","name":"狂汗"},{"value":"e79691e997ae.gif","name":"疑问"},{"value":"e79c9fe6a392.gif","name":"真棒"},
                                {"value":"e7ac91e79cbc.gif","name":"笑眼"},{"value":"e88ab1e5bf83.gif","name":"花心"},{"value":"e98499e8a786.gif","name":"鄙视"},{"value":"e4b996.gif","name":"乖"},
                                {"value":"e5958a.gif","name":"啊"},{"value":"e59090.gif","name":"吐"},{"value":"e591bc.gif","name":"呼"},{"value":"e992b1.gif","name":"钱"},{"value":"e6b3aa.gif","name":"泪"},
                                {"value":"e586b7.gif","name":"冷"},{"value":"e68092.gif","name":"怒"},{"value":"e6b197.gif","name":"汗"},{"value":"e596b7.gif","name":"喷"},{"value":"e985b7.gif","name":"酷"},{"value":"e592a6.gif","name":"咦"},
                                {"value":"e5a4a7e68b87e68c87.gif","name":"大拇指"},{"value":"e5bcb1.gif","name":"弱"},{"value":"e8839ce588a9.gif","name":"胜利"},{"value":"e88cb6e69daf.gif","name":"茶杯"},
                                {"value":"e781afe6b3a1.gif","name":"灯泡"},{"value":"e992b1e5b881.gif","name":"钱币"},{"value":"e7a4bce789a9.gif","name":"礼物"},{"value":"e78eabe791b0.gif","name":"玫瑰"},
                                {"value":"e5bda9e899b9.gif","name":"彩虹"},{"value":"e697a0e8afad.gif","name":"无语"},{"value":"e6809de7b4a2.gif","name":"思索"},{"value":"e59083e6838a.gif","name":"吃惊"},
                                {"value":"e8b59e.gif","name":"赞"},{"value":"e7ac91.gif","name":"笑"},{"value":"e5b7aee8af84.gif","name":"差评"},{"value":"e5989fe598b4.gif","name":"嘟嘴"},{"value":"e59bb0e68391.gif","name":"困惑"},
                                {"value":"e585b4e5a58b.gif","name":"兴奋"},{"value":"e58f91e68481.gif","name":"发愁"},{"value":"e5aeb3e7be9e.gif","name":"害羞"},{"value":"e593ade6b3a3.gif","name":"哭泣"},{"value":"e5969ce6aca2.gif","name":"喜欢"},
                                {"value":"e99fb3e4b990.gif","name":"音乐"}];

                let maskHtml = '<div id="mask_box" style="position: fixed;width:100%;height:100%;top:0;left:0;display:none;"></div>';
                let faceListHtml = '<div id="face_box" style="display:none;position: absolute;right: 0;border: 1px solid #d8d8d8;width: 255px;height: 150px;background: #fff;border-radius: 5px;box-shadow: 3px 3px 5px #888888;z-index:999"></div>';
                let afHtml = '<input style="margin-left: 5px;" type="button" id="add_files" value="添加图片" onclick="FUN_UTIL.chooseImage()">'+
                    '<div style="display: initial;position: relative;"><input style="margin-left: 5px;" type="button" id="choose_face" value="添加表情"/>'+ faceListHtml +'</div>'+
                    '<input style="display:none;" accept="image/*" onchange="FUN_UTIL.inputDomChange(this)" multiple id="my_hide_file" type="file" />';
                let toastHtml = '<div style="display:none;position: fixed;z-index: 10000;top: 50%;left: 50%;transform: translateX(-50%);opacity: 0.63;background: #000000;text-align: center;color: #FFFFFF;padding: 0 5px;border-radius: 3px;"' +
                    ' id="toast_box"></div>';
                let loadHtml = '<div style="display:none;position: fixed;z-index: 10000;top: 50%;left: 50%;transform: translateX(-50%);opacity: 0.63;background: #000000;text-align: center;color: #FFFFFF;padding: 0 5px;border-radius: 3px;"' +
                    ' id="loading_box">Loading...</div>';

                $('#add_files').after(afHtml);
                $('body').append(toastHtml).append(maskHtml).append(loadHtml);

                let faceHtmlList = ['<ul style="display: flex;list-style: none;flex-wrap: wrap;overflow: auto;height: 100%;padding: 5px;">'];
                faceHtmlList = faceHtmlList.concat(faceList.map((i) => '<li style="" data-name="'+ i.name +'"><img style="width:30px;height:30px;margin:5px" src="/img/face/'+ i.value +'" /></li>'));
                faceHtmlList.push('</ul>');
                $('#face_box').html(faceHtmlList.join(''));
                $('#choose_face').click(function(){
                    $("#face_box,#mask_box").show();
                });
                $('#mask_box').click(function(){
                    console.log('mask_box');
                    FUN_UTIL.closeAll();
                });
                //表情点击
                $('#face_box').on('click','li',function(){
                    $('#content').val($('#content').val() + '{'+ $(this).data('name') +'}');
                });
            },
            //点击选择图片按钮
            chooseImage: () => {
                console.log('chooseImage');
                $('#my_hide_file').trigger('click');
            },
            getUpUrl: (obj) => {
                if(FUN_UTIL.getCache('upUrl')){
                    obj.succ && obj.succ(FUN_UTIL.getCache('upUrl'));
                }else{
                    $.ajax({
                        url: 'https://uc.qbox.me/v1/query',
                        data: {ak: FUN_UTIL.getCache('upToken').split(':')[0], bucket: 'hu60'},
                        success: (res) => {
                            FUN_UTIL.setCache('upUrl', res.https.up[0]);
                            obj.succ && obj.succ(res.https.up[0]);
                        },
                        error: FUN_UTIL.err
                    });
                }
            },
            getToken: (obj) => {
                if(FUN_UTIL.getCache('upToken')){
                    obj.succ && obj.succ(FUN_UTIL.getCache('upToken'));
                }else{
                    $.ajax({
                        url: '/q.php/api.qiniu.json',
                        success: (res) => {
                            FUN_UTIL.setCache('upHost', res.host);
                            FUN_UTIL.setCache('upToken', res.uptoken);
                            obj.succ && obj.succ(res.uptoken);
                        },
                        error: FUN_UTIL.err
                    });
                }
            },
            err: () => {
                alert('出现错误');
            },
            closeAll: () => {
                FUN_UTIL.hideLoad();
                $("#face_box").hide();
                $("#mask_box").hide();
            },
            getFileSuffix: (fileName) => {
                return fileName.split('.').slice(-1);
            },
            inputDomChange: function(fileDom) {
                console.log('inputDomChange');
                FUN_UTIL.uploadFile(fileDom.files[0]);
            },
            showToast: (msg, time) => {
                FUN_UTIL.hideLoad();
                $('#toast_box').html(msg).show();
                setTimeout(() => {
                    $('#toast_box').hide();
                }, time || 2000);
            },
            loading: () => {
                $('#loading_box').show();
            },
            hideLoad: () => {
                $('#loading_box').hide();
            },
            setCache: (name, value)=> {
                let str = name + "=" + escape(value); //编码
                let date = new Date();
                let ms = 10 * 24 * 3600 * 1000;//10天
                date.setTime(date.getTime() + ms);
                str += "; expires=" + date.toGMTString();
                document.cookie = str;
            },
            getCache: (name) => {
                var arrStr = document.cookie.split("; ");
                for (var i = 0; i < arrStr.length; i++) {
                    var temp = arrStr[i].split("=");
                    if (temp[0] == name) return unescape(temp[1]);  //解码
                }
                return "";
            }
        }
    }();
    setTimeout(() => {
        FUN_UTIL && FUN_UTIL.init();
    }, 0);

})();



